<template>
  <svg width='630' height='210' id="bar" ></svg>
</template>

<script setup>
import { onMounted } from "vue";
import { ref } from "vue";
import userApi from "../../apis/user";
import * as d3 from 'd3';

const Product = ref({
  MeatNumber: '',
  VegetableNumber: '',
  SeaFoodNumber: '',
  FruitNumber: '',
  AllNumber: ''
});

onMounted(async () => {
  console.log("进入bar了")
  await getAllProductNumber();
});

const getAllProductNumber = async () => {
  try {
    const res = await userApi.getAllProductNumber();
    const data = res;
    const svg = d3.select("#bar");
    const width = 630;
    const height = 210;
    const marginTop = 30;
    const marginRight = 0;
    const marginBottom = 30;
    const marginLeft = 40;
    svg.append("text")
        .attr("x", 330)
        .attr("y", 20)
        .attr("text-anchor", "middle")
        .text("商品数量分布图")
        .style('font-family', 'Arial')
        .style('font-size', '17px')
        .style("font-weight", "bold")
        .style('fill', '#a19f9f');
    const x = d3.scaleBand()
        .domain(d3.groupSort(data, ([d]) => -d.quantity, (d) => d.product))
        .range([marginLeft, width - marginRight])
        .padding(0.1);
    const y = d3.scaleLinear()
        .domain([0, d3.max(data, (d) => d.quantity)])
        .range([height - marginBottom, marginTop]);
    svg.attr("width", width)
        .attr("height", height)
        .attr("viewBox", [0, 0, width, height])
        .attr("style", "max-width: 100%; height: auto;");
    svg.append("g")
        .attr("fill", "steelblue")
        .selectAll()
        .data(data)
        .join("rect")
        .attr("x", (d) => x(d.product))
        .attr("y", (d) => y(d.quantity))
        .attr("height", (d) => y(0) - y(d.quantity))
        .attr("width", x.bandwidth());
    svg.selectAll(".label")
        .data(data)
        .join("text")
        .attr("class", "label")
        .text((d) => d.quantity)
        .attr("x", (d) => x(d.product) + x.bandwidth() / 2)
        .attr("y", (d) => y(d.quantity) - 5) // 调整位置
        .attr("text-anchor", "middle")
        .style("font-size", "12px")
        .style("fill", "black");
    svg.append("g")
        .attr("transform", `translate(0,${height - marginBottom})`)
        .call(d3.axisBottom(x).tickSizeOuter(0));
    svg.append("g")
        .attr("transform", `translate(${marginLeft},0)`)
        .call(d3.axisLeft(y).tickFormat((y) => (y).toFixed()))
        .call(g => g.select(".domain").remove())
        .call(g => g.append("text")
            .attr("x", -marginLeft)
            .attr("y", 10)
            .attr("fill", "currentColor")
            .attr("text-anchor", "start")
            .text("↑ 数量 "));
  } catch (error) {
    console.error(error);
  }
}
</script>

<style scoped>

</style>
